#!/usr/bin/env python3
# -*- coding: utf-8 -*-

"""
本地微信消息推送工具
功能：监听本地微信登录情况，并向指定微信群推送消息
使用说明：
1. 安装依赖：pip install wxauto
2. 确保本地已安装微信客户端并登录
3. 修改下面的配置项，设置要监听的微信群名
"""

import time
from datetime import datetime
import logging
import os
import subprocess
import threading
import sys
from config import WECHAT_ENABLED, LOCAL_WECHAT_GROUP_NAME, WECHAT_APP_PATH

# 配置日志
logging.basicConfig(
    level=logging.INFO,
    format='%(asctime)s - %(levelname)s - %(message)s',
    handlers=[
        logging.FileHandler('local_wechat.log'),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)


class LocalWeChatNotifier:
    def __init__(self):
        self.enabled = WECHAT_ENABLED
        # 从配置文件中获取要推送消息的微信群名称
        self.target_group_name = LOCAL_WECHAT_GROUP_NAME
        self.wechat = None
        
        if self.enabled:
            try:
                # 尝试连接本地微信客户端
                self.wechat = None  # macOS使用AppleScript控制，无需wxauto实例
                logger.info("成功连接到本地微信客户端")
            except Exception as e:
                logger.warning(f"连接本地微信客户端失败: {e}")
                # 根据用户需求，不再自动启动微信，而是直接禁用推送功能
                logger.info("微信未运行，不自动启动，禁用推送功能")
                self.enabled = False
        else:
            logger.info("本地微信推送功能已禁用")
    
    def start_wechat(self):
        """自动启动微信客户端"""
        try:
            if not WECHAT_APP_PATH or not os.path.exists(WECHAT_APP_PATH):
                # 如果配置中没有提供微信路径或路径不存在，尝试从默认位置启动
                logger.warning("未配置微信应用路径或路径不存在，尝试从默认位置启动")
                # Windows默认安装路径尝试
                default_paths = [
                    "C:\\Program Files\\Tencent\\WeChat\\WeChat.exe",
                    "C:\\Program Files (x86)\\Tencent\\WeChat\\WeChat.exe"
                ]
                
                wechat_exe = None
                for path in default_paths:
                    if os.path.exists(path):
                        wechat_exe = path
                        break
                
                if not wechat_exe:
                    logger.error("找不到微信客户端可执行文件")
                    return False
                
                logger.info(f"从默认路径启动微信: {wechat_exe}")
                subprocess.Popen(wechat_exe)
                return True
            else:
                # 使用配置中提供的路径启动微信
                logger.info(f"从配置路径启动微信: {WECHAT_APP_PATH}")
                subprocess.Popen(WECHAT_APP_PATH)
                return True
        except Exception as e:
            logger.error(f"启动微信客户端失败: {e}")
            return False
    
    def send_message(self, message):
        """使用AppleScript异步发送消息到微信群，避免阻塞UI"""
        if not self.enabled:
            logger.warning("推送功能已禁用，无法发送消息")
            return False

        def _async_send():
            try:
                # 构建AppleScript命令
                # 转义消息中的双引号以避免AppleScript语法错误
                escaped_message = message.replace('"', '\\"')
                applescript = f'''
                tell application "WeChat"
                    try
                        set searchName to "{self.target_group_name}"
                        set chatList to every chat whose name is searchName
                        if (count of chatList) > 0 then
                            set theChat to item 1 of chatList
                        if theChat is not missing value then
                            send "{escaped_message}" to theChat
                            return "success:sent_to_" & searchName
                        else
                            return "chat_object_null:searchName=" & searchName
                            else
                                return "chat_object_null:searchName=" & searchName
                            end if
                        else
                            return "group_not_found:searchName=" & searchName
                        end if
                    on error errMsg
                        set errText to errMsg as text
                        return "error:" & errText
                    end try
                end tell
                '''
                
                # 执行AppleScript
                result = subprocess.run(
                    ['osascript', '-e', applescript],
                    capture_output=True,
                    text=True
                )
                
                if result.returncode == 0:
                    output = result.stdout.strip()
                    # 解析AppleScript返回的状态
                    if output.startswith("success:"):
                        logger.info("消息发送成功")
                        return True
                    elif output.startswith("group_not_found:"):
                        logger.error(f"目标群组 '{self.target_group_name}' 不存在，请检查群组名称是否正确")
                        return False
                    elif output.startswith("chat_object_null:"):
                        logger.error(f"获取群聊对象失败: {output}")
                        return False
                    elif output.startswith("error:"):
                        logger.error(f"AppleScript执行错误: {output}")
                        return False
                    else:
                        logger.error(f"消息发送失败: {output}")
                        return False
                else:
                    error_msg = result.stderr.lower()
                    if "not authorized" in error_msg or "permission" in error_msg:
                        logger.error("权限不足：请在系统偏好设置 > 安全性与隐私 > 隐私 > 自动化中允许终端控制微信")
                    else:
                        logger.error(f"消息发送失败: {result.stderr}")
                    return False
            except Exception as e:
                logger.error(f"发送消息时发生错误: {e}")
                return False

        # 启动异步线程发送消息，避免阻塞主界面
        threading.Thread(target=_async_send, daemon=True).start()
        return True

    def check_wechat_login(self):
        """使用AppleScript检查微信是否已登录"""
        if not self.enabled:
            logger.warning("推送功能已禁用，跳过登录检查")
            return False

        try:
            # 构建检查登录状态的AppleScript
            applescript = '''
            tell application "WeChat"
                activate
                delay 2
                try
                        activate
                        set mainWindow to window 1
                        return "logged_in"
                on error errMsg
                    set errText to errMsg as text
                    return "error:" & errText
                end try
            end tell
            '''

            # 执行AppleScript
            result = subprocess.run(
                ['osascript', '-e', applescript],
                capture_output=True,
                text=True
            )

            if result.returncode == 0:
                    output = result.stdout.strip()
                    if output == "logged_in":
                        logger.info("微信已登录，检测到有效的聊天会话")
                        return True
                    elif output == "permission_denied":
                        logger.error("权限不足：请在系统偏好设置 > 安全性与隐私 > 隐私 > 自动化中允许终端控制微信")
                        return False
                    else:
                        logger.warning("微信未登录或没有聊天会话，请确保微信已登录并保持前台运行")
                        return False
            else:
                    logger.error(f"检查登录状态失败: {result.stderr}")
                    return False
        except Exception as e:
            logger.error(f"检查微信登录状态时发生错误: {e}")
            return False
    
    def get_group_by_name(self, group_name):
        """根据群名获取微信群对象"""
        try:
            if not self.check_wechat_login():
                logger.error("微信未登录，无法获取群聊列表")
                return None
            
            # 尝试使用多种方法查找微信群（适配wxauto库不同版本）
            try:
                # 方法1：尝试直接发送消息到群聊，如果群聊存在则会成功
                self.wechat.SendMsg("", group_name)
                logger.info(f"成功找到群聊: {group_name}")
                return group_name  # 直接返回群名，后面SendMsg方法可以接受字符串
            except Exception:
                # 方法2：如果直接发送失败，尝试其他方式
                try:
                    # 方法2.1：尝试使用Search方法
                    chat = self.wechat.Search(group_name)
                    if chat:
                        logger.info(f"成功找到群聊: {group_name}")
                        return chat
                except Exception:
                    pass
                
                # 如果所有方法都失败，我们记录错误但仍然返回群名，让后续代码尝试发送
                logger.warning(f"无法直接找到群聊: {group_name}，但将尝试直接发送消息")
                return group_name
        except Exception as e:
            logger.error(f"获取群聊列表失败: {e}")
            return None
    
    def send_message_to_group(self, group_name, content):
        """向指定微信群发送消息"""
        if not self.enabled:
            return False, "本地微信推送功能未启用"
        
        if not self.check_wechat_login():
            return False, "微信未登录"
        
        try:
            # 转义消息中的双引号以避免AppleScript语法错误
            escaped_content = content.replace('"', '\\\\"')
            applescript = f'''
            tell application "WeChat"
                activate
                try
                    set searchName to "{group_name}"
                    set foundChat to missing value
                    
                    -- 方法1：通过群名直接发送
                    try
                        send "{escaped_content}" to chat searchName
                        return "success:sent_to_" & searchName
                    on error
                        -- 方法2：如果直接发送失败，尝试查找群聊
                        try
                            set foundChat to first chat whose name is searchName
                            if foundChat is not missing value then
                                send "{escaped_content}" to foundChat
                                return "success:sent_to_" & searchName
                            else
                                return "group_not_found:searchName=" & searchName
                            end if
                        on error errMsg
                            set errText to errMsg as text
                            return "error:" & errText
                        end try
                    end try
                on error errMsg
                    set errText to errMsg as text
                    return "error:" & errText
                end try
            end tell
            '''
            
            # 执行AppleScript
            result = subprocess.run(
                ['osascript', '-e', applescript],
                capture_output=True,
                text=True
            )
            
            if result.returncode == 0:
                output = result.stdout.strip()
                if output.startswith("success:"):
                    return True, "消息发送成功"
                elif output.startswith("group_not_found:"):
                    return False, f"目标群组 '{group_name}' 不存在"
                else:
                    return False, f"发送失败: {output}"
            else:
                return False, f"AppleScript执行失败: {result.stderr}"
        except Exception as e:
            error_msg = f"发送消息失败: {e}"
            logger.error(error_msg)
            return False, error_msg
    
    def format_telegram_for_wechat(self, telegram):
        """格式化电报数据为适合微信发送的简洁文本"""
        # 确保所有必要字段都存在
        title = telegram.get('title', '无标题')
        content = telegram.get('content', '无内容')
        time_str = telegram.get('time', datetime.now().strftime('%Y-%m-%d %H:%M:%S'))
        
        # 构建简洁的消息内容
        message = f"📰 财联社电报\n"
        message += f"⏰ 时间: {time_str}\n"
        message += f"💡 标题: {title}\n"
        message += f"📝 内容: {content}\n"
        
        return message
    
    def send_telegram_to_wechat_group(self, telegram):
        """发送单条电报数据到指定微信群"""
        message = self.format_telegram_for_wechat(telegram)
        return self.send_message_to_group(self.target_group_name, message)


# 创建全局的本地微信通知器实例
local_wechat_notifier = LocalWeChatNotifier()